<?php

namespace App\Http\Controllers;

use App\Http\Libs\Helper_Huanxin;
use App\Models\Activity;
use App\Models\Chatroom;
use App\Models\ChatroomContent;
use App\Models\ChatroomLog;
use App\Models\ChatroomUser;
use App\Models\User;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Http\Requests\CategoryRequest;
use App\Http\Requests\ChatroomRequest;
use Illuminate\Pagination\LengthAwarePaginator as lPaginator;

class ChatroomController extends CommonController
{
    /**
     * 获取聊天室列表
     *
     */
    public function getIndex()
    {
        $lists = Chatroom::orderBy('id', 'desc')->paginate(10);

        return view('chatroom.index')->with('lists', $lists)->with('actions', $this->actions);
    }

    /**
     * 创建一个聊天室
     */
    public function getCreate()
    {
        return view('chatroom.create');
    }

    /**
     * 执行一个聊天室的创建
     */
    public function postCreate(ChatroomRequest $request)
    {
        $data = $request->input();
        $exist = Chatroom::where('activity_id', $data['activity_id'])->where('type', $data['type'])->first();
        if (is_object($exist)) {
            return AjaxCallbackMessage('该活动下，该类型的聊天室已经存在了', false);
        }
        $user = Helper_Huanxin::getUser($data['uid']);
        if (isset(json_decode($user)->error)) {
            Helper_Huanxin::register(array('username' => $data['uid'], 'password' => $data['uid']));
        }

        $result = Helper_Huanxin::createChatroom(trim($data['name']), trim($data['description']), $data['uid'], '', $data['maxusers']);
        if (!isset(json_decode($result)->data->id)) {
            isset(json_decode($result)->error_description) ? $error_description = json_decode($result)->error_description : $error_description = '未知';

            return AjaxCallbackMessage('创建失败，原因为' . $error_description, false);
        }
        $chat_id = json_decode($result)->data->id;
        $chatroom = Chatroom::create(
            [
                'chat_id'     => $chat_id,
                'name'        => $data['name'],
                'description' => $data['description'],
                'activity_id' => $data['activity_id'],
                'type'        => $data['type'],
                'maxusers'    => $data['maxusers']
            ]
        );
        ChatroomUser::create(['chatroom_id' => $chatroom->id, 'uid' => $data['uid'], 'is_admin' => 1]);

        return AjaxCallbackMessage('创建成功', true, url('chatroom/index'));
    }

    /**
     * 获取聊天室编辑
     */
    public function getEdit(Request $request)
    {
        $data = $request->input();
        $list = Chatroom::where('id', $data['id'])->first();
        $chatRoom = Helper_Huanxin::getRoom($list->chat_id);

        if (isset(json_decode($chatRoom)->data[0]->affiliations[0]->owner)) {
            $owner = json_decode($chatRoom)->data[0]->affiliations[0]->owner;
        } else {
            $owner = ChatroomUser::where('chatroom_id', $list->id)->where('is_admin', 1)->first();
            $owner = $owner->uid;
        }
        $owner = User::where('uid', $owner)->first();
        $activity = Activity::where('id', $list->activity_id)->first();

        return view('chatroom.edit')->with('list', $list)->with('chatRoom', json_decode($chatRoom)->data[0])
            ->with('owner', $owner)->with('activity', $activity);
    }

    /**
     * 执行一个聊天室编辑
     */
    public function postEdit(ChatroomRequest $request)
    {
        $data = $request->input();
        if (strpos(trim($data['name']), ' ') || strpos(trim($data['description']), ' ')) {
            return AjaxCallbackMessage('不允许名称或者描述中存在空格', false);
        }
        Helper_Huanxin::editRoom($data['chat_id'], array('name' => $data['name'], 'description' => $data['description'], 'maxusers' => $data['maxusers']));

        Chatroom::where('id', $data['id'])->update(
            [
                'name'        => $data['name'],
                'description' => $data['description'],
                'maxusers'    => $data['maxusers'],
                'type'        => $data['type'],
                'activity_id' => $data['activity_id'],
            ]
        );

        return AjaxCallbackMessage('编辑成功', true, url('chatroom/index'));
    }

    /**
     * 删除一个聊天室
     */
    public function postDelete(Request $request)
    {
        $data = $request->input();
        $list = Chatroom::where('id', $data['rid'])->first();
        Chatroom::where('id', $data['rid'])->delete();
        Helper_Huanxin::deleteRoom($list->chat_id);

        return AjaxCallbackMessage('删除成功', true, url('chatroom/index'));
    }

    /**
     * 获取某个聊天室的成员
     */
    public function getUser(Request $request)
    {
        $data = $request->input();
        $lists = ChatroomUser::with('user')->where('chatroom_id', $data['id'])->paginate(10);

        return view('chatroom.user')->with('lists', $lists)->with('actions', $this->actions);
    }

    /**
     * 为某个聊天室踢掉一个成员
     */
    public function postDelMember(Request $request)
    {
        $data = $request->input();
        Helper_Huanxin::deleteRoomMember($data['room_id'], $data['uid']);
        ChatroomUser::where('chatroom_id', $data['room_id'])->where('uid', $data['uid'])->delete();
        $log = ChatroomLog::where('chatroom_id', $data['room_id'])->where('uid', $data['uid'])->where('status', 1)->first();
        ChatroomLog::where('chatroom_id', $data['room_id'])->where('uid', $data['uid'])->update(['status' => 0]);

        return AjaxCallbackMessage('成员踢出成功', true, url('chatroom/user?id=' . $data['room_id']));
    }

    /**
     * 获取聊天内容
     */
    public function getContent(Request $request)
    {
        $data = $request->input();
        $lists = ChatroomContent::where('chatroom_id', $data['chatroom_id'])->where('uid', $data['uid'])->paginate(10);

        return view('chatroom.content')->with('lists', $lists);
    }

    /**
     * 获取某个人在某个聊天室的轨迹
     */
    public function getLog(Request $request)
    {
        $data = $request->input();
        $lists = ChatroomLog::where('chatroom_id', $data['chatroom_id'])->where('uid', $data['uid'])->get();
        $datas = array();
        $count = count($lists);
        $time = 0;
        foreach ($lists as $k => $v) {
            $time += (strtotime($v->updated_at->toDateTimeString()) - strtotime($v->created_at->toDateTimeString())) / 60;
            if ($v->status == 1) {
                $datas[] = array('action' => '进入房间', 'time' => $v->created_at->toDateTimeString());
            } else {
                $datas[] = array('action' => '进入房间', 'time' => $v->created_at->toDateTimeString());
                $datas[] = array('action' => '退出房间', 'time' => $v->updated_at->toDateTimeString());
            }
        }

        $page = $request->input('page') ? $request->input('page') : 1;

        $paginator = new lPaginator(
            array_slice($datas, ($page - 1)*10, 10), count($datas), 10, $page, [
            'path'  => 'log',
            'query' => array('uid' => $data['uid'], 'chatroom_id' => $data['chatroom_id']),
        ]);

        return view('chatroom.log')->with('lists', $paginator)->with('count', $count)->with('time', $time);
    }

}
